import React from 'react';
import {
  Button,
  Table,
  Switch,
  Spin,
  Icon,
  Popconfirm,
  Anchor,
  Modal,
  Form,
  Input,
  message
} from 'antd';
import cn from 'classnames';
import validatorCreator from '@util/validator-creator';
import _ from 'lodash';
import PropTypes from 'prop-types';
import {
  getAssetCategoryList,
  addAssetCategory,
  updateAssetCategory,
  deleteAssetCategory
} from '@api/asset';
import './index.less';

class AssetCategoryManage extends React.Component {
  static propTypes = {
    form: PropTypes.object
  };
  constructor(props) {
    super(props);
    this.state = {
      list: [],
      modalTitle: '',
      loaded: false,
      loading: false,
      saving: false
    };
  }
  componentDidMount() {
    this.loadAssetCategory();
  }
  loadAssetCategory = () => {
    const { loaded } = this.state;
    if (!loaded) {
      this.setState({ loading: true });
    }
    getAssetCategoryList()
      .then(res => {
        const list = _.get(res, 'data.data.list', []);
        const categoryMap = {};
        list.forEach(item => {
          if (item.parent) {
            if (categoryMap[item.parent]) {
              categoryMap[item.parent].children.push(item);
            }
          } else {
            item.children = [];
            categoryMap[item._id] = item;
          }
        });
        const customSort = (a, b) => {
          if (a.name === '恶意软件' && b.name === '其它') {
            return -1;
          } else if (a.name === '其它' && b.name === '恶意软件') {
            return 1;
          } else {
            return 0;
          }
        };

        this.setState({ loaded: true, list: Object.values(categoryMap).sort(customSort) });
      })
      .catch(() => {
        message.error('加载资产分类失败');
      })
      .finally(() => {
        this.setState({ loading: false });
      });
  };
  trigeAddCategory = item => {
    const name = _.get(item, 'name');
    const id = _.get(item, '_id');
    if (name) {
      this.props.form.setFieldsValue({ parent: id }, () => {
        this.setState({ modalTitle: `添加${name}的分类` });
      });
    } else {
      this.setState({ modalTitle: '添加一级分类' });
    }
  };
  saveCategory = () => {
    const { modalTitle } = this.state;
    const { form } = this.props;
    form.validateFields((err, data) => {
      if (err) {
        return;
      }
      const action = data._id
        ? data => updateAssetCategory(_.pick(data, ['_id', 'name', 'active']))
        : addAssetCategory;
      this.setState({ saving: true });
      Promise.resolve(action(data))
        .then(() => {
          message.success(`${modalTitle}成功`);
          this.setState(
            {
              modalTitle: ''
            },
            () => {
              this.loadAssetCategory();
              form.resetFields();
            }
          );
        })
        .catch(err => {
          let errMsg = `${modalTitle}失败`;
          if (err.type === 'parsed' && _.toString(err.message).trim()) {
            errMsg += `: ${_.toString(err.message).trim()}`;
          }
          message.error(errMsg);
        })
        .finally(() => {
          this.setState({ saving: false });
        });
    });
  };
  trigeEditCategory = item => {
    const name = _.get(item, 'name');
    const { form } = this.props;
    if (name) {
      form.setFieldsValue(item, () => this.setState({ modalTitle: `编辑${name}` }));
    }
  };
  deleteCategory = item => {
    const name = _.get(item, 'name');
    const id = _.get(item, '_id');
    deleteAssetCategory(id)
      .then(() => {
        message.success(`删除${name}成功`);
        this.loadAssetCategory();
      })
      .catch(() => {
        message.error(`删除${name}失败`);
      });
  };
  updateStatus = (item, active) => {
    item.active = active;
    updateAssetCategory(_.pick(item, ['_id', 'name', 'active']))
      .then(this.loadAssetCategory)
      .catch(() => {
        message.error(`修改${item.name}状态失败`);
      });
  };
  renderTopCategory = item => {
    const columns = [
      {
        title: '分类',
        dataIndex: 'name'
      },
      {
        title: '类型',
        dataIndex: 'system',
        render: system => (system ? '系统默认' : '自定义')
      },
      {
        title: '操作',
        key: 'opts',
        render: row => {
          const disabled = row.system;
          return (
            <div className={cn('opts-cell', { disabled })}>
              <a className="edit" onClick={disabled ? null : () => this.trigeEditCategory(row)}>
                编辑
              </a>
              <Popconfirm
                disabled={disabled}
                title="删除后，相关资产会移除该资产分类，确认删除吗？"
                onConfirm={disabled ? null : () => this.deleteCategory(row)}
              >
                <a className="delete">删除</a>
              </Popconfirm>
            </div>
          );
        }
      }
    ];
    return (
      <div id={item._id} className="top-item" key={item._id}>
        <div className="top-name">
          <span className="value">{item.name}</span>
          <div className="opts">
            {!_.get(item, 'children.length') && !_.get(item, 'system') && (
              <Popconfirm
                title="删除后，相关资产会移除该资产分类，确认删除吗？"
                onConfirm={() => this.deleteCategory(item)}
              >
                <Button type="danger" className="delete">
                  删除
                </Button>
              </Popconfirm>
            )}
            {!_.get(item, 'system') && (
              <Button className="edit" onClick={() => this.trigeEditCategory(item)}>
                编辑
              </Button>
            )}
            <Button className="add" type="primary" onClick={() => this.trigeAddCategory(item)}>
              添加分类
            </Button>
          </div>
        </div>
        <Table
          columns={columns}
          pagination={false}
          key="_id"
          dataSource={_.get(item, 'children', [])}
        />
      </div>
    );
  };
  onCancelModal = () => {
    const { form } = this.props;
    form.resetFields();
    this.setState({ saving: false, modalTitle: '' });
  };
  render() {
    const {
      form: { getFieldDecorator }
    } = this.props;
    const { list, loading, modalTitle, saving } = this.state;
    return (
      <div className="asset-category-manage">
        <div className="title">资产分类管理</div>
        <div className="add-top-level">
          <Button type="primary" onClick={this.trigeAddCategory}>
            <Icon type="plus-circle" />
            添加资产一级分类
          </Button>
        </div>
        {loading ? (
          <div className="loading-container">
            <Spin loading />
          </div>
        ) : (
          <div className="content">
            <div className="main">{list.map(item => this.renderTopCategory(item))}</div>
            <div className="anchor-container">
              <Anchor
                offsetTop={10}
                getContainer={() => {
                  const container =
                    document.querySelector('.asset-config-container') || document.body;
                  return container;
                }}
              >
                {list.map(item => (
                  <Anchor.Link key={item._id} title={item.name} href={`#${item._id}`} />
                ))}
              </Anchor>
            </div>
          </div>
        )}
        <Modal
          maskClosable={false}
          className={cn(
            'asset-category-manage-modal',
            'no-header-bottom-lines',
            'bottom-center',
            'padding-24'
          )}
          visible={modalTitle}
          title={modalTitle}
          onCancel={this.onCancelModal}
          onOk={this.saveCategory}
          confirmLoading={saving}
        >
          <Form colon={false} labelAlign="left" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }}>
            <Form.Item hidden className="hidden-form-item">
              {getFieldDecorator('_id')(<Input />)}
            </Form.Item>
            <Form.Item hidden className="hidden-form-item">
              {getFieldDecorator('parent')(<Input />)}
            </Form.Item>
            <Form.Item hidden className="hidden-form-item">
              {getFieldDecorator('active')(<Switch />)}
            </Form.Item>
            <Form.Item required label="名称" key="name">
              {getFieldDecorator('name', {
                rules: [
                  {
                    validator: validatorCreator('名称', {
                      required: true
                    })
                  },
                  {
                    max: 32,
                    message: '您输入的内容超过32个字符限制'
                  }
                ]
              })(<Input placeholder="请输入中文、英文、特殊字符或数字，不超过32个字符" />)}
            </Form.Item>
          </Form>
        </Modal>
      </div>
    );
  }
}
export default Form.create()(AssetCategoryManage);
